package edu.ptu.acl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.ptu.acl.entity.RoleUser;
import edu.ptu.acl.mapper.RoleUserMapper;
import edu.ptu.acl.service.ILogService;
import edu.ptu.acl.service.IRoleUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LinJC
 * @since 2022-03-15
 */
@Service
public class RoleUserServiceImpl extends ServiceImpl<RoleUserMapper, RoleUser> implements IRoleUserService {

    @Resource
    private RoleUserMapper roleUserMapper;
    @Resource
    private ILogService logService;

    @Override
    public void updateRoleUser(Long roleId, List<Long> userId) {
        // todo:做一下判断，如果没修改就不要做插入了

        QueryWrapper<RoleUser> roleUserQueryWrapper = new QueryWrapper<>();
        roleUserQueryWrapper.eq("role_id",roleId);
        List<RoleUser> beforeRoleUsers = roleUserMapper.selectList(roleUserQueryWrapper);
        roleUserMapper.delete(roleUserQueryWrapper);

        if (CollectionUtils.isEmpty(userId)){
            logService.saveRoleUserLog(roleId,beforeRoleUsers.stream().map(RoleUser::getUserId).collect(Collectors.toList()), null);
            return;
        }
        // todo:改成批量插入
        for (Long id : userId) {
            roleUserMapper.insert(new RoleUser(roleId, id));
        }
        logService.saveRoleUserLog(roleId,beforeRoleUsers.stream().map(RoleUser::getUserId).collect(Collectors.toList()),
                userId);
    }
}
